import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import { message, Upload} from 'antd';
import type {GetProp, UploadProps} from 'antd';
import {CommonComponentProps} from "../../../../components/editor/interface.ts";
import {useState} from "react";
import {useDrag} from "react-dnd";

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};


const UploadDev = (props: CommonComponentProps) => {
    const {id, styles, name, uploadUrl} = props

    const uploadAttrs = {
        name,
        action: uploadUrl,
        disabled: props.disabled,
        maxSize: props.maxSize,
        accept: props.accept as string[],
        limitSize: props.limitSize,
        maxCount: props.maxCount,
        showUploadList: props.showUploadList,
        text: props.text,
    };

    const [_, drag] = useDrag({
        type: name,
        item: {
            id,
            type: name,
            dragType: "move"
        }
    })

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj as FileType, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };

    const beforeUpload = async (file: FileType) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const fileType = uploadAttrs.accept?.join('、')
        if (!isJpgOrPng) {
            message.error(`你只能上传${fileType}文件`);
        }
        const isLt2M = file.size / 1024 / 1024 < uploadAttrs.limitSize / 1024;
        if (!isLt2M) {
            message.error(`图片大小必须小于${uploadAttrs.limitSize / 1024 }Mb`);
        }
        return isJpgOrPng && isLt2M;
    };

    const uploadButton = (
        <button style={{border: 0, background: 'none'}} type="button">
            {loading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8}}>{uploadAttrs.text}</div>
        </button>
    );

    return (
        <div data-component-id={id} ref={drag} style={styles}>
            {/*<FormItem name={name}>*/}
                <Upload
                    listType="picture-card"
                    className="avatar-uploader"
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                    {...uploadAttrs as any}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{width: '100%'}}/> : uploadButton}
                </Upload>
            {/*</FormItem>*/}
        </div>
    );
};

export default UploadDev;